;
var commonArr=[];
var customArr=[];
var addArr=[];
var listArr=[];
(function($) {
    var Page = {};
    var brick;
    brick = "<div class='brick small' data-sffb='' data-sum='0' data-con='0' data-date='0' data-sjl='1'><span></span><div onclick='deletelist(event,this)' class='delete'>&times;</div></div>";
    Page.Event = {
        init : function() {
            this.initColum();
            this.addEvent()
        },
        addEvent :function () {
            $(document).on('click','.parentDirectory',function () {
                var obj=$(this).parents('.rank').find('.sonDirectory');
                if(obj.css('display')=='none'){
                    obj.slideDown();
                    $(this).find('.fa').attr('class','fa fa-caret-down')
                }else{
                    obj.slideUp();
                    $(this).find('.fa').attr('class','fa fa-caret-right')
                }
            })
            $(document).on("click", ".column .go", function(event) {
                var $this;
                event.preventDefault();
                event.stopPropagation();
                $this = $(this);
                $('.gridly').append(brick);
                var type=$this.parents('li').attr('type')
                var index=$this.parents('li').attr('index')
                if(type=='common'){
                    listArr.push(commonArr[index]) //取公用模板数据
                }else if(type=='add'){
                    listArr.push(addArr[index]) //取新添加模板数据
                }else{
                    // listArr.push(customArr[index]) //取自定义获取的模板数据
                    listArr.push(commonArr[index])
                }
                listArr[listArr.length-1].ext1=$this.parents('li').find('span').text();
                $('.gridly span').last().attr({
                    'id':$this.parents('li').find('span').attr('id'),
                    'templatetype':$this.parents('ul').attr('type'),
                    'index':listArr.length-1,
                    'type':$this.parents('li').attr('type'),/*模板来源*/
                    'detailId':$this.parents('li').attr('detailId'),
                    'sort':$this.parents('li').attr('sort'),
                }).html($this.parents('li').find('span').text());
                $('.gridly .brick').last().attr('data-sffb',$this.parents('li').find('span').attr('data-sffb'));
                $this.parents('li').hide();
                return $('.gridly').gridly('layout');
            });
            $(document).on('dblclick','.sonDirectory li',function () {
                var params={
                    templateType:$(this).parents('ul').attr('type'),
                    templateName:$(this).find('span').text(),
                    templateId:$(this).attr('templateId'),
                    customId:$('#customId').val(),
                    sort:$(this).attr('sort'),
                    detailId:$(this).attr('detailId'),
                }
                templateEdit(params)
            })

            $('.column,.content').on('contextmenu', function(e){
                var _this=e.target;
                var option=[];
                var templateId='';
                var name='';
                var sort='';
                var detailId='';
                var specialLock=false;
                var rootNode=$(_this).parents('.rank').length ? $(_this).parents('.rank') :$(_this);
                if($(_this).hasClass('parentDirectory')||$(_this).parents('.parentDirectory').length){
                    option=[{title:'添加模板',class:'add'}];
                    templateId=rootNode.find('ul').attr('id');
                }else if(($(_this).is('li')||$(_this).parents('li').length)){
                    if($(_this).parents('#commonTemplate').length){
                        option=[{title:`添加到${$('.keSubTitle').text()}模板`,class:'addTo'},{title:'删除模板',class:'delete'},{title:'编辑模板',class:'edit'}]
                    }else{
                        option=[{title:'删除模板',class:'delete'},{title:'编辑模板',class:'edit'}]
                    }
                    $('.sonDirectory li:hover').addClass('li-active').siblings().removeClass('li-active');
                    templateId=$('.li-active').attr('templateId');
                    name=$('.li-active span').text();
                    sort=$('.li-active').attr('sort');
                    detailId=$('.li-active').attr('detailId')
                }else if(($(_this).hasClass('brick')||$(_this).parents('.brick').length)){
                    option=[{title:'移除模板',class:'x'},{title:'编辑模板',class:'editTwo'}];
                    specialLock=true;
                    rootNode=$(_this).parents('.brick').length ? $(_this).parents('.brick') :$(_this);
                    templateId=rootNode.find('span').attr('id');
                    name=rootNode.find('span').text();
                    sort=rootNode.find('span').attr('sort');
                    detailId=rootNode.find('span').attr('detailId')
                }
                if(specialLock){
                    $('#contextmenu').empty().attr({'type':rootNode.find('span').attr('templatetype'),'nodeId':rootNode.find('span').attr('id'),'templateId':templateId,'name':name,'sort':sort,'detailId':detailId});
                }else{
                    $('#contextmenu').empty().attr({'type':rootNode.find('ul').attr('type'),'nodeId':rootNode.find('ul').attr('id'),'templateId':templateId,'name':name,'sort':sort,'detailId':detailId});
                }
                option.forEach(function (item,i) {
                    $('#contextmenu').append(`<li class="${item.class}">${item.title}</li>`)
                })
                $('#contextmenu')[0].style.left=e.clientX+'px';
                $('#contextmenu')[0].style.top=e.clientY+'px';
                return false;
            })
            document.onmousedown = function(e) {
                var _this=$(e.target);
                if(!_this.parents('#contextmenu').length){
                    $('#contextmenu').empty();
                    $('.sonDirectory li').removeClass('li-active')
                    return false
                }
                var className=_this.attr('class');
                var params={
                    templateType:$('#contextmenu').attr('type'),
                    templateName:$('#contextmenu').attr('name'),
                    customId:$('#customId').val(),
                    sort:$('#contextmenu').attr('sort'),
                    nodeId:$('#contextmenu').attr('nodeId')
                }
                switch(e.button) {
                    case 0:
                        //鼠标左键
                        if(className=='add'){
                            params.sort=$('#'+$('#contextmenu').attr('nodeId')).find('li').length+1;
                            templateAdd(params)
                        }else if(className=='edit'){
                            params.templateId=$('#contextmenu').attr('templateId');
                            params.detailId=$('#contextmenu').attr('detailId')
                            templateEdit(params)
                        }else if(className=='delete'){
                            layer.confirm("确定删除吗?",
                                {
                                    btn: ["确定", "取消"],
                                    title: "提示",
                                    icon: 7
                                },
                                function () {
                                    params.templateId=$('#contextmenu').attr('templateId');
                                    params.detailId=$('#contextmenu').attr('detailId');
                                    params.del=1;
                                    templateEdit(params)
                                });
                        }else if(className=='addTo'){
                            params.sort=$('#customTemplate').find('li').length+1;
                            templateEdit(params,'to')
                        }else if(className=='x'){
                            $('.content').find('#'+$('#contextmenu').attr('nodeId')).next().click()
                        }else if(className=='editTwo'){
                            params.ext1=params.templateName;
                            delete params.templateId;
                            delete params.templateName;
                            delete params.templateType;
                            params.templateId=$('#contextmenu').attr('templateId');
                            params.detailId=$('#contextmenu').attr('detailId')
                            templateEdit(params)
                        }
                        $('#contextmenu').empty();
                        break;
                    case 1:
                        //鼠标中间
                        if(className=='add'){
                            templateAdd(params)
                        }
                        break;
                    case 2:
                        //鼠标右键
                        break;
                    default:
                        break;
                }
            }
            /*全屏*/
            $('#fullScreen').click(function () {
                var lock=$(this).attr('lock')||'';
                if(!lock){
                    $(this).attr({
                        'lock':true,
                        'src':'../../img/suoping.svg'
                    });
                    $('.viewhtml').css({
                        'width':'101.5%',
                        'position': 'fixed',
                        'left': '-20px',
                        'top':0,
                        'z-index': 999
                    })
                }else {
                    $('.viewhtml').css({
                        'width':'69%',
                        'position': 'relative',
                        'left': '',
                        'top':'',
                        'z-index': 999
                    })
                    $(this).attr({
                        'lock':'',
                        'src':'../../img/quanping.svg'
                    });
                }
            })

        },
        initColum : function(){
            var _args = {
                customId :$('#customId').val()
            }
            $.ajax({
                url : '/template/cdStructuredTemplate/getCustomList',
                data : _args,
                contentType : 'application/json;charset=utf-8',
                type: 'GET',
                async:false,
                success : function(res) {
                    //getMenuTrees();
                    if(res.state===200){
                        var _data = res.results.resultList;
                        insertColum(_data);
                        hideLeft();
                    }
                },
                error : function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log(XMLHttpRequest.status);
                    console.log(textStatus);
                }
            });
            /*自定义模板内容*/
            $.ajax({
                url : '/template/cdStructuredCustomDetail/findByCondition',
                data : {customId:$('#customId').val()},
                contentType : 'application/json;charset=utf-8',
                type: 'GET',
                async:false,
                success : function(res) {
                    if(res.state===200 && res.results){
                        var _data = res.results.detailList;
                        _data && _data.sort(compare('sort'));
                        var customHtml='';
                        var headHtml='';
                        var footerHtml='';
                        var outerHtml='';
                        var printHtml = '';
                        var num=-1;
                        _data && _data.forEach(function (item,i) {
                            var html1=`<li type="custom" index="${i}"  detailId="${item.detailId}" templateId="${item.templateId}"  class="clear"><span id='${item.templateId}'>${item.templateName}</span></li>`;
                            customArr.push(item)/*存放自定义数据*/
                            commonArr.push(item)
                            switch (item.templateType){
                                case '999':
                                    num++;
                                    $('.gridly').append(brick);
                                    $('.gridly span').last().attr({
                                        'id':item.templateId,
                                        'index':num,
                                        'templateType':item.templateType,
                                        'type':'custom',
                                        'detailId':item.detailId,
                                        'sort':item.sort
                                    });
                                    $('.gridly span').last().html(item.templateName);
                                    listArr.push(item)
                                    break;
                                case '666':
                                    num++;
                                    $('.gridly').append(brick);
                                    $('.gridly span').last().attr({
                                        'id':item.templateId,
                                        'index':num,
                                        'templateType':item.templateType,
                                        'type':'custom',
                                        'detailId':item.detailId,
                                        'sort':item.sort
                                    });
                                    $('.gridly span').last().html(item.templateName);
                                    listArr.push(item)
                                    break;
                                case '777' :
                                    headHtml+=html1;
                                    break;
                                case '888' :
                                    footerHtml+=html1;
                                    break;
                                case '555' :
                                    outerHtml+=html1;
                                    break;
                                case '000' :
                                    printHtml+=html1;
                                    break;
                                default :
                                    break;
                            }
                        })
                        $('#headTemplate').html(headHtml);
                        $('#footerTemplate').html(footerHtml);
                        $('#outerScript').html(outerHtml);
                        $("#printTemplate").html(printHtml)
                        hideLeft()
                    }
                },
                error : function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log(XMLHttpRequest.status);
                    console.log(textStatus);
                }
            });
            function compare(property){
                return function(a,b){
                    var value1 = a[property];
                    var value2 = b[property];
                    return value1 - value2;
                }
            }

            function getRequestUrl() {
                var url = self.window.location.href;

                var o = {};
                if (url.indexOf('?') > 0) {
                    var data = (url.split('?'))[1];

                    if (data.indexOf('&') > 0) {
                        data1 = (data.split('&'));
                        $.each(data1, function (index, el) {
                            el=el.replace("=","$=$");
                            var a = el.split("$=$");
                            var key = a[0];
                            var value = a[1];
                            o[key] = value;
                        });
                    } else {
                        data=data.replace("=","$=$");
                        var a = data.split("$=$");
                        var key = a[0];
                        var value = a[1];
                        o[key] = value;
                    }
                    return o;
                } else {
                    return o;
                }
            }

            function insertColum(_data){
                // if(_data.length&&_data.length>0){
                    if(true){
                    var urlParams=getRequestUrl();
                    var tempalteName=decodeURI(getRequestUrl().customName);/*获取传过来的模板名称*/
                    var inner1=`<div class="rank">
							<div class="parentDirectory"><span>通用模板</span><i class="fa fa-caret-right"></i></div>
							<ul class="sonDirectory" id="commonTemplate" type="999"></ul></div>`;
                    var inner2=`<div class="rank" style="margin-top: 10px">
							<div class="parentDirectory"><span>${tempalteName}</span><i class="fa fa-caret-right"></i></div>
							<ul class="sonDirectory"  id="customTemplate" type="666"></ul></div>
							<div class="rank" style="margin-top: 10px">
							<div class="parentDirectory"><span>头部模板</span><i class="fa fa-caret-right"></i></div>
							<ul class="sonDirectory"  id="headTemplate" type="777"></ul></div>
							<div class="rank" style="margin-top: 10px">
							<div class="parentDirectory"><span>尾部模板</span><i class="fa fa-caret-right"></i></div>
							<ul class="sonDirectory"  id="footerTemplate" type="888"></ul></div>
							
							<div class="rank" style="margin-top: 10px">
							<div class="parentDirectory"><span>外调脚本</span><i class="fa fa-caret-right"></i></div>
							<ul class="sonDirectory"  id="outerScript" type="555"></ul></div>
							
                            <div class="rank" style="margin-top: 10px">
							<div class="parentDirectory"><span>打印模板</span><i class="fa fa-caret-right"></i></div>
							<ul class="sonDirectory"  id="printTemplate" type="000"></ul></div>`;
                    $("#contentSelect").html(inner1);
                    $('.rank').after(inner2)
                    for(var i =0;i<_data.length;i++){
                        var item=_data[i];
                        if(item.templateType=='999'){
                            commonArr.push(item)
                            $('#commonTemplate').append(`<li type="common" index="${i}" templateId="${item.templateId}" sort="${item.sort||''}" detailId="${item.detailId||''}" class="clear"><span id='${item.templateId}'>${item.templateName}</span><i class="iconfont icon-jiantou-xiangyou go"></i></li>`)
                        }else if(item.templateType=='666'){
                            customArr.push(item)
                            commonArr.push(item)
                            $('#customTemplate').append(`<li type="custom" index="${i}" detailId="${item.detailId}" templateId="${item.templateId}" class="clear"><span id='${item.templateId}'>${item.templateName}</span><i class="iconfont icon-jiantou-xiangyou go"></i></li>`)
                        }
                    }
                }
            }
            function hideLeft(){
                $(".brick span").each(function(){
                    $('.sonDirectory span[id='+this.id+']').parent().css('display','none');
                });
            }
        },
    };
    Page.Event.init();
})(jQuery);

function hideorshowLeft(p,q){
    $('.column .blue span[id='+p+']').parent().css('display',q);
}

function hideorshowLeft2(p,q){
    var arr = $('.sonDirectory span').get();
    var spanobj;
    for(var i=0;i<arr.length;i++){
        if(arr[i].id==p){
            spanobj=arr[i];
            break;
        }
    }
    spanobj.parentNode.style.display=q;
}
function changetype(pid,ptype){
    if(ptype=="0"){
        ptype="1";
    }
    else{
        ptype="0";
    }

    window.open("zdyQueryShow.jsp?formsetid="+pid+"&flag="+ptype,"_self");
}
function templateAdd(params) {
    var nodeId=params.nodeId;
    delete params.nodeId;
    var addIndex=top.layer.open({
        type:2,
        title:'模板添加',
        content:`/template/cdStructuredCustom/customEmrEdit`,
        btn: ["保存", "取消"],
        area:['1000px','650px'],
        zIndex:9999,
        yes: function (index,dom) {
            var iframeDoc=$('iframe',dom).contents();
            params.templateName=iframeDoc.find('#title').val();
            if(params.templateName.replace(/\s*/g,"").length==0){
                top.layer.error("模板名称不能为空！");
                return false;
            }
            params.templateContent=$('iframe',dom)[0].contentWindow.editor.getData();
            $.ajax({
                url : '/template/cdStructuredTemplate/addHtmlTemplate',
                data : JSON.stringify(params),
                contentType : 'application/json;charset=utf-8',
                type: 'POST',
                success: function (res) {
                    if (res.state == 200) {
                        top.layer.msg("保存成功！");
                        var data=res.results;
                        var obj={templateContent:$('iframe',dom)[0].contentWindow.editor.getData()}
                        addArr.push(obj);
                        var type=$('#'+nodeId).attr('type')
                        if (type=='999'||type=='666'){
                            $('#'+nodeId).append(`<li type="add" sort="${params.sort}" index="${addArr.length-1}" class="clear" detailId="${data.detailId}" templateId="${data.templateId}"><span id='${data.templateId}'>${iframeDoc.find('#title').val()}</span><i class="iconfont icon-jiantou-xiangyou go"></i></li>`);
                        }else{
                            $('#'+nodeId).append(`<li type="add" sort="${params.sort}" index="${addArr.length-1}" class="clear" detailId="${data.detailId}" templateId="${data.templateId}"><span id='${data.templateId}'>${iframeDoc.find('#title').val()}</span></li>`);
                        }
                        top.layer.close(index)
                    } else {
                        top.layer.error("保存失败！", res.msg);
                    }
                },
                error: function (msg) {
                    top.layer.error("保存失败!");
                }
            });
        },
        btn2:function(index,dom){
            top.layer.close(index)
        },
    });
}

function templateEdit(params,type) {
    var nodeId=params.nodeId;
    delete params.nodeId;
    var index;
    if(params.ext1){
        index=$('.content').find('#'+nodeId).attr('index');
    }
    if(type=='to'){
        var obj=$('.li-active').clone();
        params.templateContent=commonArr[obj.attr('index')].templateContent;
        params.sort=$('#customTemplate li').length;
        params.templateType='666';
        params.type=type;
        method(params,'添加',function (res) {
            addArr.push({templateContent:params.templateContent}) //添加添加模板数据
            obj.removeClass('li-active').attr({
                'type':'add',
                'sort':params.sort,
                'detailId':res.results.detailId,
                'index':addArr.length-1,
                'templateid':res.results.templateId
            });
            obj.find('span').attr('id',res.results.templateId)
            $('#customTemplate').append(obj)
        })
        return false
    }
    if(params.del==1){
        method(params,'删除',function () {
            $('.li-active').remove();
        })
        return false
    }
    var index=top.layer.open({
        type:2,
        title:'模板编辑',
        content:`/template/cdStructuredCustom/customEmrEdit?tempId=${params.templateId}&templateName=${params.templateName||params.ext1}&index=${index||''}`,
        btn: ["保存", "取消"],
        area:['1000px','650px'],
        zIndex:9999,
        yes: function (index,dom) {
            var iframeDoc=$('iframe',dom).contents();
            if(params.ext1){
                try {
                    params.ext2=$('iframe',dom)[0].contentWindow.editor.getData();
                    var indexs=$('.content').find('#'+nodeId).attr('index');
                    listArr[indexs].ext2=params.ext2;
                    setTimeout(function () {
                        top.layer.msg("保存成功！")
                        top.layer.close(index)
                    },1000)
                }catch(e) {
                    top.layer.msg(`保存失败！(${e})`)
                }
                return false;
            }else{
                params.templateContent=$('iframe',dom)[0].contentWindow.editor.getData();
            }
            method(params,'保存',function () {
                setTimeout(function () {
                    top.layer.close(index)
                },1000)
            })
        },
        btn2:function(){
            top.layer.close(index)
        },
        zIndex:'200',
        scrolling:'no'
    });
    function method(params,textType,callBack) {
        if(params.type){
            var url='/template/cdStructuredTemplate/addHtmlTemplate';
            var methodType='POST'
            delete params.type
        }else{
            var url='/template/cdStructuredTemplate/updateHtmlTemplate';
            var methodType='PUT'
        }
        $.ajax({
            url : url,
            data : JSON.stringify(params),
            contentType : 'application/json;charset=utf-8',
            type: methodType,
            success: function (res) {
                if (res.state == 200) {
                    top.layer.msg(textType+"成功！");
                    if(callBack){
                        callBack(res)
                    }
                } else {
                    top.layer.error(textType+"失败！", res.msg);
                }
            },
            error: function (msg) {
                top.layer.error(textType+"失败!");
            }
        });
    }
}